home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 7197 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.3 KB

  1. Path: rcp6.elan.af.mil!rscernix!danpop
  2. From: danpop@mail.cern.ch (Dan Pop)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: C beginner needs your help ASAP
  5. Date: 19 Feb 96 00:24:49 GMT
  6. Organization: CERN European Lab for Particle Physics
  7. Message-ID: <danpop.824689489@rscernix>
  8. References: <4g862f$p0b@risky.ecs.umass.edu> <4g8ahd$p8b@spectator.cris.com>
  9. NNTP-Posting-Host: ues5.cern.ch
  10. X-Newsreader: NN version 6.5.0 #7 (NOV)
  11.  
  12. In <4g8ahd$p8b@spectator.cris.com> aubrey@concentric.net (Aubrey Harrison) writes:
  13.  
  14. >This is how I would do it. I tested it and it seems to do what you want. Of 
  15.                                             ^^^^^^^^
  16. "It seems" is the keyword here, indeed.
  17.  
  18. >course, I am no expert, in fact I was called "ignorant and idiot" by Mister Dan 
  19.  
  20. Not only you're no expert, you have also difficulties counting up to ten.
  21.  
  22. >#include <stdio.h>
  23. >
  24. >main()
  25. >{
  26. >        char buf[3],filename[9];
  27. >        int  i;
  28. >
  29. >        for(i=0; i<10; i++)
  30. >        {
  31. >                sprintf(buf,"%d",i);
  32. >                strcpy( filename,"data");
  33. >                strcat( filename, buf );
  34. >                strcat( filename, ".ext");
  35.  
  36. strcat and strcpy are _not_ functions returning an int, hence a proper
  37. declaration is mandatory (even if the value returned is discarded).
  38. ALWAYS include <string.h> before using string manipulation functions.
  39.  
  40. Anyway, these 4 lines can be replaced by a single sprintf call:
  41.  
  42.         sprintf(buf, "data%d.ext", i);
  43.  
  44. >                printf( "%s\n", filename);
  45. >        }
  46. Returning a value from a function (implicitly) defined as returning int
  47. is always a good idea.
  48. >}
  49.  
  50. Let's look at how buf and filename are dimensioned.  
  51.  
  52. buf will always hold one digit and the terminating null character.  It's
  53. oversized by one character, but this not a major problem.  Better safe
  54. than sorry :-)
  55.  
  56. OTOH, we're in deep trouble with filename, which will have to contain
  57. strings of the form "dataX.ext", but sizeof "dataX.ext" is 10, not 9.
  58. Now we're invoking undefined behaviour and we should be sorry for this :-)
  59.  
  60. Too many mistakes in such a short and simple program, don't you think?
  61. Badly written code is of no help to anybody.  First learn C _yourself_,
  62. then try to help others.
  63.  
  64. Dan
  65. --
  66. Dan Pop
  67. CERN, CN Division
  68. Email: danpop@mail.cern.ch 
  69. Mail:  CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
  70.